import { Message } from "element-ui"; // 单独引入 Message
import folderIcon1 from "../assets/images/folderIcon.png"; // 文件夹和文件图标/树状结构
import folderIcon from "../assets/images/tree-topLevel.png"; // 文件夹和文件图标/树状结构
import txtIcon from "../assets/images/tree-Sub Level.png";
import QRCode from "qrcode";
import md5 from "js-md5";
import webUrl from "@/config/otherLink";
// mixins混入对象
export const mixinsMethod = {
  methods: {
    // /**
    //  * 输入框/只允许输入数字，小数点，负数
    //  * @param {event} event/event对象
    //  */
    onlyNumber(event) {
      if (event.target.value === "" || event.target.value === undefined) {
        return false;
      } else {
        // eslint-disable-next-line no-useless-escape
        if (/^(\-|\+)?\d+(\.)?(\d){0,2}$/.test(event.target.value)) {
          return false;
        } else {
          event.target.value = "";
          Message({
            message: "只允许输入小数点两位的数字！",
            type: "warning",
            duration: 1500,
            showClose: true,
          });
        }
      }
    },

    /**
     * 改变月份选择器 月 > 期
     * @param {e} elementUI/日期组件实例
     */
    focusMonthInt(e) {
      if (e.id !== "monthTextChanged") {
        setTimeout(() => {
          let monthDom = document.getElementsByClassName("cell");
          for (let index = 0; index < monthDom.length; index++) {
            let monthText = document.getElementsByClassName("cell")[index].textContent;
            if (monthText.indexOf("月") > 0) {
              monthText = monthText.split("月");
              let newMonthText = monthText[0] + "期";
              document.getElementsByClassName("cell")[index].textContent = newMonthText;
            }
          }
        }, 0);
        e.id = "monthTextChanged";
      }
    },

    /**
     * 循环tree数据给每个节点加上图
     * @param {data} data/树状结构数据
     */
    mapTreeData(data) {
      data.map((item) => {
        // if (item.childrenList.length !== 0) {
        //   item.icons = folderIcon
        //   this.mapTreeData(item.childrenList)
        // } else {
        //   item.icons = txtIcon
        // }
        //第一级为蓝色的图片
        if (item.level == 1) {
          item.icons = folderIcon;
          this.mapTreeData(item.childrenList);
        } else {
          item.icons = txtIcon;
        }
        // if (item.DirID === 0) { // <!--2020-1-19 | gz | 改变节点显示图片 -->
        //   item.icons = folderIcon
        // }
        // if (item.DirID !== 0) {
        //   item.icons = txtIcon
        // }
      });
    },

    /**
     * 开始期间不得大于结束期间
     * @param {start end} start/开始期间 end/结束期间
     */
    startThenEnd(start, end) {
      if (Number(start) > Number(end)) {
        Message({
          message: "开始期间不得大于结束期间！",
          type: "warning",
          duration: 1500,
          showClose: true,
        });
        return false;
      } else {
        return true;
      }
    },

    /**
     * 中国标准时间 > 年月(201901)
     * @param {date} date/中国标准日期格式
     */
    formatDateTime(date) {
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      return y + m;
    },

    /**
     * 日期加横杠
     * @param {soure, start, newStr} soure/原字符 start/下标 newStr/加的字符
     */
    _dateFormat(soure, start, newStr) {
      return soure.slice(0, start) + newStr + soure.slice(start);
    },

    /**
     * 显示期间 禁用其他时间段
     * @param {date, that} date/element回传的中国标准日期 that/vue实例
     */
    upToDate(date, that) {
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = date.getDate();
      d = d < 10 ? "0" + d : d;
      var h = date.getHours();
      var minute = date.getMinutes();
      minute = minute < 10 ? "0" + minute : minute;
      let thisMonth = y + "-" + m + "-" + d + " " + h + ":" + minute;
      let startMonth = that._dateFormat(that.period.start, 4, "-");
      let endMonth = that._dateFormat(that.period.end, 4, "-");
      if (new Date(thisMonth).getTime() >= new Date(startMonth).getTime() && new Date(thisMonth).getTime() <= new Date(endMonth).getTime()) {
        return false;
      } else {
        return true;
      }
    },
    getUserList() {
      // 获取用户
      this.$api.systemManagement.GetUserList().then((res) => {
        let resData = res.data.data;
        this.$store.dispatch("getUserList", resData);
      });
    },

    /**
     * 递归清空对象的所有值
     * @param {obj} 要清空的对象 用于 一层 {} 或 多层 {{{{{{{{{}}}}}}}}} 格式的对象
     */
    clearObjVal(objer) {
      for (var key in objer) {
        if (Object.prototype.toString.call(objer[key]) === "[object Object]") {
          // 如果属性对应的属性值仍为可分解的对象，使用递归函数继续分解，直到最里层
          this.clearObjVal(objer[key]);
        } else {
          objer[key] = "";
        }
      }
      return objer;
    },

    /**
     * 递归清空部门下级为null的Childer字段
     * @param {obj} arr|要清空的json数据
     */
    delChilderIsNull(arr) {
      for (var i = 0; i < arr.length; i++) {
        if (arr[i].Children.length !== 0) {
          this.delChilderIsNull(arr[i].Children);
        } else {
          delete arr[i].Children;
        }
      }
      return arr;
    },

    /**
     * 根据城市编码获取城市名称
     */
    deepQuery(tree, id) {
      var isGet = false;
      var retNode = null;
      function deepSearch(tree, id) {
        for (var i = 0; i < tree.length; i++) {
          if (tree[i].children && tree[i].children.length > 0) {
            deepSearch(tree[i].children, id);
          }
          if (id === tree[i].id || isGet) {
            isGet || (retNode = tree[i]);
            isGet = true;
            break;
          }
        }
      }
      deepSearch(tree, id);
      return retNode;
    },

    /**
     * 判读浏览器类型
     * @returns
     */
    BrowserType() {
      let userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
      let isOpera = userAgent.indexOf("Opera") > -1; //判断是否Opera浏览器
      let isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera || userAgent.indexOf("rv:11") > -1; //判断是否IE浏览器
      let isEdge = userAgent.indexOf("Windows NT 6.1; Trident/7.0;") > -1 && !isIE; //判断是否IE的Edge浏览器
      let isFF = userAgent.indexOf("Firefox") > -1; //判断是否Firefox浏览器
      let isSafari = userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") == -1; //判断是否Safari浏览器
      let isChrome = userAgent.indexOf("Chrome") > -1 && userAgent.indexOf("Safari") > -1; //判断Chrome浏览器
      if (isIE) {
        if (userAgent.indexOf("rv:11") > -1) {
          return "IE11";
        }
        if (userAgent.indexOf("rv:12") > -1) {
          //这一段还没验证
          return "IE12";
        }
        let reIE = new RegExp("MSIE (\\d+\\.\\d+);");
        reIE.test(userAgent);
        let fIEVersion = parseFloat(RegExp["$1"]);
        if (fIEVersion == 7) {
          return "IE7";
        } else if (fIEVersion == 8) {
          return "IE8";
        } else if (fIEVersion == 9) {
          return "IE9";
        } else if (fIEVersion == 10) {
          return "IE10";
        } else if (fIEVersion == 11) {
          return "IE11";
        } else if (fIEVersion == 12) {
          return "IE12";
        } else {
          return "0";
        } //IE版本过低
      } //isIE end
      if (isFF) {
        return "FF";
      }
      if (isOpera) {
        return "Opera";
      }
      if (isSafari) {
        return "Safari";
      }
      if (isChrome) {
        return "Chrome";
      }
      if (isEdge) {
        return "Edge";
      }
    },

    /**
     * 绘制分享的二维码
     * str：要转为二维码的链接
     */
    getQRCode(str) {
      setTimeout(() => {
        let opts = {
          errorCorrectionLevel: "H", //容错级别
          type: "image/png", //生成的二维码类型
          quality: 0.3, //二维码质量
          margin: 5, //二维码留白边距
          width: 190, //宽
          height: 190, //高
          text: "http://www.xxx.com", //二维码内容
          color: {
            dark: "#333333", //前景色
            light: "#fff", //背景色
          },
        };
        let msg = document.getElementById("qrcodeCanvas");
        // 将获取到的数据（val）画到msg（canvas）上
        QRCode.toCanvas(msg, str, opts, function (error) {});
      }, 300);
    },

    /**
     * 数组排序
     * @param {*根据keyName排序} keyName
     * @returns
     */
    objectArraySort(keyName) {
      return function (objectN, objectM) {
        var valueN = Number(objectN[keyName]);
        var valueM = Number(objectM[keyName]);
        if (valueN > valueM) return 1;
        else if (valueN < valueM) return -1;
        else return 0;
      };
    },

    /**
     * @param {手机号} phone
     */
    checkPhone(phone) {
      if (!/^1[3456789]\d{9}$/.test(phone)) {
        this.$router.push({
          name: "unitInformation",
          query: {},
        });
        this.$message({
          message: "请输入正确的手机号",
          type: "warning",
        });
      }
    },

    /**
     * 获取url中拼接的参数
     *
     * @param {String} variable 要获取的地址栏key值 eg：Token
     * @returns
     */
    getQueryVariable(variable) {
      var query = window.location.search.substring(1);
      var vars = query.split("&");
      for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        // eslint-disable-next-line eqeqeq
        if (pair[0] == variable) {
          return pair[1];
        }
      }
      return false;
    },
  },
};

/**
 *
 * @param {企业号} Serial
 * @returns
 */
export const getPersonalCenterUrl = (Serial) => {
  let key = "yundaizhang";
  let random = Math.random();
  let dt = new Date();
  let secret = key + "&" + Serial + "&" + random + "&" + dt.getFullYear() + (dt.getMonth() + 1) + dt.getDate();
  let url = `${webUrl.order}/Order/Index?Serial=${Serial}&secret=${md5(secret)}&random=${random}`;
  return url;
};

/**
 * 循环tree数据给每个节点加上图标  //
 * @param {data} data/树状结构数据
 */
export const mapTreeAddIcon = (data) => {
  data.map((item) => {
    if (item.type === 0 || item.type === 1) {
      item.icons = folderIcon1;
    }
    if (item.type === 2) {
      item.icons = folderIcon;
    }
    if (item.type === 3) {
      item.icons = txtIcon;
    }
    if (item.childrens && item.childrens.length !== 0) {
      mapTreeAddIcon(item.childrens);
    }
  });
  return data;
};

export function currentMonthDays() {
  return String(new Date().toJSON()).split("T").shift() + "";
}

export const removeChildren = (data) => {
  for (let index = 0; index < data.length; index++) {
    const item = data[index];
    if (item.childrens && item.childrens.length != 0) {
      removeChildren(item.childrens);
    } else {
      item.childrens = null;
    }
  }
};

export const getYearsToNow = (createTime) => {
  // this.yearsToNow=[2020,2021,2022]
  //获取到从那一年开始
  let smallYears = createTime;
  //获取当前时间
  let date = new Date();
  let nowYears = date.getFullYear();
  let Years = nowYears - smallYears;
  let arrYear = [];
  let yearsToNow = [];
  for (let i = 0; i <= Years; i++) {
    arrYear.push(nowYears--);
  }
  arrYear.forEach((item) => {
    //下拉框的数组
    yearsToNow.push(item);
  });
  return yearsToNow;
};

export const mergeId = (list, key1, key2) => {
  list.forEach((m) => {
    m.newId = `${m[key1]}$${m[key2]}`;
  });
  return list;
};
